package com.duoec.dw.lineage.service.analyser.statement;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;
import com.alibaba.druid.sql.ast.statement.SQLDropTableStatement;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.duoec.dw.lineage.enums.StatementType;
import com.duoec.dw.lineage.exceptions.LineageAnalyseException;
import com.duoec.dw.lineage.dto.DropTableLineageDto;
import com.duoec.dw.lineage.dto.TableCoordinateDto;
import com.duoec.dw.lineage.dto.TableLineageDto;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author xuwenzhen
 */
@Service
public class DropTableStatementAnalyser extends BaseStatementAnalyser<SQLDropTableStatement> {
    /**
     * 匹配具体的SQLStatement
     *
     * @return 匹配类型
     */
    @Override
    public Set<Class<? extends SQLStatement>> parseSqlStatements() {
        return Sets.newHashSet(SQLDropTableStatement.class);
    }

    /**
     * 分析
     *
     * @param statement SQLStatement
     * @return 当前操作的血缘关系
     */
    @Override
    public TableLineageDto analyse(SQLDropTableStatement statement) {
        DropTableLineageDto dto = new DropTableLineageDto();
        dto.setStatementType(StatementType.DROP_TABLE);
        List<SQLExprTableSource> tableSources = statement.getTableSources();
        List<TableCoordinateDto> tables = dto.getDropList();
        if (tables == null) {
            tables = Lists.newArrayList();
            dto.setDropList(tables);
        }
        for (SQLExprTableSource tableSource : tableSources) {
            SQLExpr expr = tableSource.getExpr();
            if (expr instanceof SQLPropertyExpr) {
                SQLPropertyExpr propertyExpr = (SQLPropertyExpr) expr;
                TableCoordinateDto table = new TableCoordinateDto();
                table.setDatabaseName(propertyExpr.getOwnernName());
                table.setTableName(propertyExpr.getName());
                tables.add(table);
            } else {
                throw new LineageAnalyseException("删除表需要指定全名，当前值：" + expr.toString());
            }
        }
        return dto;
    }
}
